<?php


namespace app\index\controller;


use think\Db;

class User extends \Common
{

    # 获取全部用户
    public function GetAllUsers()
    {
        $admin = Db::name("admin")->select();
        $user = [];
        foreach ($admin as $value) {
            $user[] = [
                "id"   => $value["aid"],
                "name" => $value["name"]
            ];
        }

        $this->Code(200, false, $user);
    }

    # 获取全部用户
    public function GetAllUsers1()
    {
        $admin = Db::name("admin")->select();
        $user = [];
        foreach ($admin as $value) {
            $user[] = [
                "value"   => $value["aid"],
                "label" => $value["name"]
            ];
        }

        $this->Code(200, false, $user);
    }

    # 获取用户
    public function GetUsers()
    {
        $role = $this->token["role"];
        if ($role == 1) {
            if (isset($_GET["page"]) && isset($_GET["limit"]) && isset($_GET["search"]) && isset($_GET["branchId"])) {
                if ($_GET["search"] != "") {
                    if($_GET["branchId"] != ""){
                        $admin = Db::name("admin")
                            ->where("role", 0)
                            ->where("name like '%{$_GET["search"]}%'")
                            ->where("bid", $_GET["branchId"])
                            ->order("sort desc")
                            ->page($_GET["page"], $_GET["limit"])
                            ->select();
                        $total = Db::name("admin")
                            ->where("name like '%{$_GET["search"]}%'")
                            ->where("role", 0)
                            ->count();
                    }else{
                        $admin = Db::name("admin")
                            ->where("role", 0)
                            ->where("name like '%{$_GET["search"]}%'")
                            ->order("sort desc")
                            ->page($_GET["page"], $_GET["limit"])
                            ->select();
                        $total = Db::name("admin")
                            ->where("name like '%{$_GET["search"]}%'")
                            ->where("role", 0)
                            ->count();
                    }

                } else {
                    if($_GET["branchId"] != ""){
                        $admin = Db::name("admin")
                            ->where("role", 0)
                            ->where("bid", $_GET["branchId"])
                            ->order("sort desc")
                            ->page($_GET["page"], $_GET["limit"])
                            ->select();
                        $total = Db::name("admin")
                            ->where("role", 0)
                            ->count();
                    }else{
                        $admin = Db::name("admin")
                            ->where("role", 0)
                            ->order("sort desc")
                            ->page($_GET["page"], $_GET["limit"])
                            ->select();
                        $total = Db::name("admin")
                            ->where("role", 0)
                            ->count();
                    }
                }
                $list = [];
                foreach ($admin as $value) {
                    $project = Db::name("distribution")
                        ->alias("a")
                        ->join("project b", "a.pid = b.pid")
                        ->where("a.aid", $value["aid"])
                        ->select();
                    $authList = [];
                    foreach ($project as $item) {
                        if ($item["otherName"] != "") {
                            $other = explode(",", $item["otherName"]);
                            $otherArr = json_decode($item["other"], true);
                            $a = [
                                "id"   => (int)$item["pid"],
                                "name" => $item["name"],
                                "r"    => $item["r"] == 1,
                                "w"    => $item["w"] == 1
                            ];
                            foreach ($other as $vals) {
                                $a[$vals] = (isset($otherArr[$vals]) && $otherArr[$vals] == 1);
                            }
                            $authList[] = $a;
                        } else {
                            $authList[] = [
                                "id"   => (int)$item["pid"],
                                "name" => $item["name"],
                                "r"    => $item["r"] == 1,
                                "w"    => $item["w"] == 1
                            ];
                        }
                    }

                    $branch = db("branch")->where("bid", $value["bid"])->find();
                    $list[] = [
                        "id"       => (int)$value["aid"],
                        "ip"       => $value["ip"] == 1,
                        "config"   => $value["groups"] == 1,
                        "goal"   => $value["goal"] == 1,
                        "bill"   => $value["bill"] == 1,
                        "stats"   => $value["billStats"] == 1,
                        "shopStats"   => $value["shopStats"] == 1,
                        "indentOut"   => $value["indentOut"] == 1,
                        "monthReport"   => $value["monthReport"] == 1,
                        "returnedStats"   => $value["returnedStats"] == 1,
                        "income"   => $value["income"] == 1,
                        "sumSheet"   => $value["sumSheet"] == 1,
                        "chinaPay"   => $value["chinaPay"] == 1,
                        "petition"   => $value["petition"] == 1,
                        "partner"   => $value["partner"] == 1,
                        "shareDoc"   => $value["shareDoc"] == 1,
                        "factory"   => $value["factory"] == 1,
                        "goodsSpec"   => $value["goodsSpec"] == 1,
                        "attendance"   => $value["attendance"] == 1,
                        "reimburse"   => $value["reimburse"] == 1,
                        "leave"   => $value["leave"] == 1,
                        "checkNotice"   => $value["checkNotice"] == 1,
                        "noticeContent"   => $value["noticeContent"] == null ? "" : $value["noticeContent"],
                        "forbidCheck"   => $value["forbidCheck"] == 1,
                        "checkTime"   => $value['checkTime'] == null ? ['',''] : explode(',',$value['checkTime']),
                        "shenzhenInventory"   => $value["shenzhenInventory"] == 1,
                        "japanInventory"   => $value["japanInventory"] == 1,
                        "goods"   => $value["goods"] == 1,
                        "billStats"   => $value["billStats2"] == 1,
                        "notice"   => $value["notice"] == 1,
                        "authBranchIds"   => array_map('intval', explode(',',$value['authBranchIds'])),
                        "btnAuths"   => explode(',',$value['btnAuths']),
                        "curio"   => $value["curio"] == 1,
                        "salon"   => $value["salon"] == 1,
                        "person"   => $value["person"] == 1,
                        "attend"   => $value["attend"] == 1,
                        "username" => $value["username"],
                        "trueName" => $value["trueName"],
                        "number" => $value["number"],
                        "position" => $value["position"],
                        "hourlyWage" => $value["hourlyWage"],
                        "password" => base64_decode($value["password64"]),
                        "name"     => $value["name"],
                        "wx"       => $value["openid"] != "",
                        "authList" => $authList,
                        "branchId" => (int)$value["bid"] == 0 ? "" : $value["bid"],
                        "branch"   => empty($branch) ? "" : $branch["name"],
                        "remark"   => $value["remark"] == null ? "" : $value["remark"],                        
                        "order"    => $value["sort"]
                    ];
                }
                $data = [
                    "list"  => $list,
                    "total" => $total
                ];
                $this->Code(200, false, $data);
            } else {
                $this->Code(403, 403);
            }
        } else {
            $this->Code(200, false, "对不起,您没有权限");
        }
    }

    # 修改用户信息
    public function UpdateUser()
    {
        $role = $this->token["role"];
        $aid = $this->token["aid"];
        if ($role == 1) {
            $auth = json_decode($_POST["auth"], true);
            $auths = [];
            if (!empty($auth)) {
                foreach ($auth as $value) {
                    $auths[$value["id"]] = $value;
                }
            }
            if (isset($_POST["id"])) {
                if (isset($_POST["name"]) && isset($_POST["password"]) && isset($_POST["username"])) {
                    $upInfo = [
                        "name"       => $_POST["name"],
                        "ip"         => $_POST["ip"] == "true" ? 1 : 0,
                        "groups"     => $_POST["config"] == "true" ? 1 : 0,
                        "goal"       => $_POST["goal"] == "true" ? 1 : 0,
                        "bill"       => $_POST["bill"] == "true" ? 1 : 0,
                        "billStats"  => $_POST["stats"] == "true" ? 1 : 0,
                        "shopStats"  => $_POST["shopStats"] == "true" ? 1 : 0,
                        "indentOut"  => $_POST["indentOut"] == "true" ? 1 : 0,
                        "monthReport"  => $_POST["monthReport"] == "true" ? 1 : 0,
                        "returnedStats"  => $_POST["returnedStats"] == "true" ? 1 : 0,
                        "income"  => $_POST["income"] == "true" ? 1 : 0,
                        "sumSheet"  => $_POST["sumSheet"] == "true" ? 1 : 0,
                        "chinaPay"  => $_POST["chinaPay"] == "true" ? 1 : 0,
                        "petition"  => $_POST["petition"] == "true" ? 1 : 0,
                        "partner"  => $_POST["partner"] == "true" ? 1 : 0,
                        "shareDoc"  => $_POST["shareDoc"] == "true" ? 1 : 0,
                        "factory"  => $_POST["factory"] == "true" ? 1 : 0,
                        "goodsSpec"  => $_POST["goodsSpec"] == "true" ? 1 : 0,
                        "attendance"  => $_POST["attendance"] == "true" ? 1 : 0,
                        "reimburse"  => $_POST["reimburse"] == "true" ? 1 : 0,
                        "leave"  => $_POST["leave"] == "true" ? 1 : 0,
                        "checkNotice"  => $_POST["checkNotice"] == "true" ? 1 : 0,
                        "noticeContent"     => $_POST["noticeContent"],
                        "forbidCheck"  => $_POST["forbidCheck"] == "true" ? 1 : 0,
                        "checkTime"        => $_POST["checkTime"],
                        "shenzhenInventory"  => $_POST["shenzhenInventory"] == "true" ? 1 : 0,
                        "japanInventory"  => $_POST["japanInventory"] == "true" ? 1 : 0,
                        "goods"  => $_POST["goods"] == "true" ? 1 : 0,
                        "billStats2"  => $_POST["billStats"] == "true" ? 1 : 0,
                        "notice"  => $_POST["notice"] == "true" ? 1 : 0,
                        "authBranchIds"       => $_POST["authBranchIds"], // 部门权限
                        "btnAuths"       => $_POST["btnAuths"], // 按钮权限
                        "curio"      => $_POST["curio"] == "true" ? 1 : 0,
                        "salon"      => $_POST["salon"] == "true" ? 1 : 0,
                        "person"     => $_POST["person"] == "true" ? 1 : 0,
                        "attend"     => $_POST["attend"] == "true" ? 1 : 0,
                        "password"   => md5($_POST["password"]),
                        "password64" => base64_encode($_POST["password"]),
                        "username"   => $_POST["username"],
                        "trueName" => $_POST["trueName"],
                        "number" => $_POST["number"],
                        "position" => $_POST["position"],
                        "hourlyWage" => $_POST["hourlyWage"],
                        "remark"     => $_POST["remark"],
                        "sort"       => $_POST["order"],
                        "bid"        => $_POST["branchId"]
                    ];
                    $check = Db::name("admin")
                        ->where("aid != {$_POST["id"]}")
                        ->where(function ($query) {
                            $query->where("username", $_POST["username"])->whereOr("name", $_POST["name"]);
                        })
                        ->find();
                    if (empty($check)) {
                        Db::name("admin")
                            ->where("aid", $_POST["id"])
                            ->update($upInfo);
                        $check1 = Db::name("distribution")
                            ->where("aid", $_POST["id"])
                            ->select();
                        if (empty($auths) && !empty($check1)) {
                            Db::name("distribution")
                                ->where("aid", $_POST["id"])
                                ->delete();
                        } else if (!empty($auths) && !empty($check1)) {
                            foreach ($check1 as $item) {
                                $p = Db::name("project")->where('pid', $item["pid"])->find();
                                $otherArr = [];
                                if ($p["otherName"] != "") {
                                    $otherArr = explode(",", $p["otherName"]);
                                }
                                $other = [];
                                if (isset($auths[$item["did"]])) {
                                    foreach ($otherArr as $vals) {
                                        $other[$vals] = $auths[$item["did"]][$vals] == true ? 1 : 0;
                                    }
                                    $Info = [
                                        "aid"   => $_POST["id"],
                                        "pid"   => $auths[$item["did"]]["id"],
                                        "w"     => $auths[$item["did"]]["w"] == true ? 1 : 0,
                                        "r"     => $auths[$item["did"]]["r"] == true ? 1 : 0,
                                        "other" => json_encode($other)
                                    ];
                                    Db::name("distribution")
                                        ->where("did", $item["did"])
                                        ->update($Info);
                                    unset($auths[$item["did"]]);
                                } else {
                                    Db::name("distribution")
                                        ->where("did", $item["did"])
                                        ->delete();
                                    unset($auths[$item["did"]]);
                                }
                            }
                            if (!empty($auths)) {
                                foreach ($auths as $item) {
                                    $p = Db::name("project")->where('pid', $item["id"])->find();
                                    $otherArr = [];
                                    if ($p["otherName"] != "") {
                                        $otherArr = explode(",", $p["otherName"]);
                                    }
                                    $other = [];
                                    foreach ($otherArr as $vals) {
                                        $other[$vals] = $item[$vals] == true ? 1 : 0;
                                    }
                                    $Info = [
                                        "aid"   => $_POST["id"],
                                        "pid"   => $item["id"],
                                        "w"     => $item["w"] == true ? 1 : 0,
                                        "r"     => $item["r"] == true ? 1 : 0,
                                        "other" => json_encode($other)
                                    ];
                                    Db::name("distribution")
                                        ->insert($Info);
                                }
                            }
                        } else if (!empty($auths) && empty($check1)) {
                            foreach ($auths as $item) {
                                $p = Db::name("project")->where('pid', $item["id"])->find();
                                $otherArr = [];
                                if ($p["otherName"] != "") {
                                    $otherArr = explode(",", $p["otherName"]);
                                }
                                $other = [];
                                foreach ($otherArr as $vals) {
                                    $other[$vals] = $item[$vals] == true ? 1 : 0;
                                }
                                $Info = [
                                    "aid"   => $_POST["id"],
                                    "pid"   => $item["id"],
                                    "w"     => $item["w"] == true ? 1 : 0,
                                    "r"     => $item["r"] == true ? 1 : 0,
                                    "other" => json_encode($other)
                                ];
                                Db::name("distribution")
                                    ->insert($Info);
                            }
                        }
                        $this->Code(200, "修改成功");
                    } else {
                        $this->Code(403, "昵称或者账号重复,请核对后修改");
                    }
                } else {
                    $this->Code(403, 403);
                }
            } else {
                if (isset($_POST["name"]) && isset($_POST["password"]) && isset($_POST["username"])) {
                    $upInfo = [
                        "name"       => $_POST["name"],
                        "ip"         => $_POST["ip"] == "true" ? 1 : 0,
                        "groups"      => $_POST["config"] == "true" ? 1 : 0,
                        "password"   => md5($_POST["password"]),
                        "password64" => base64_encode($_POST["password"]),
                        "username"   => $_POST["username"],
                        "trueName" => $_POST["trueName"],
                        "number" => $_POST["number"],
                        "position" => $_POST["position"],
                        "hourlyWage" => $_POST["hourlyWage"]
                    ];
                    $check = Db::name("admin")
                        ->where(function ($query) {
                            $query->where("username", $_POST["username"])->whereOr("name", $_POST["name"]);
                        })
                        ->find();
                    if (empty($check)) {
                        $id = Db::name("admin")
                            ->insertGetId($upInfo);
                        foreach ($auths as $item) {
                            $p = Db::name("project")->where('pid', $item["id"])->find();
                            $otherArr = [];
                            if ($p["otherName"] != "") {
                                $otherArr = explode(",", $p["otherName"]);
                            }
                            $other = [];
                            foreach ($otherArr as $vals) {
                                $other[$vals] = $item[$vals] == true ? 1 : 0;
                            }
                            $Info = [
                                "aid" => $id,
                                "pid" => $item["id"],
                                "w"   => $item["w"] == true ? 1 : 0,
                                "r"   => $item["r"] == true ? 1 : 0,
                                "other" => json_encode($other)
                            ];
                            Db::name("distribution")
                                ->insert($Info);
                        }
                        $this->Code(200, "添加成功");
                    } else {
                        $this->Code(403, "昵称或者账号重复,请核对后添加");
                    }
                } else {
                    $this->Code(403, 403);
                }
            }
        } else {
            $this->Code(200, false, "对不起,您没有权限");
        }
    }

    # 删除用户
    public function DeleteUser()
    {
        $role = $this->token["role"];
        if ($role == 1) {
            if (isset($_POST["id"])) {
                Db::name("admin")
                    ->where("aid", $_POST["id"])
                    ->delete();
                Db::name("distribution")
                    ->where("aid", $_POST["id"])
                    ->delete();
                $this->Code(200, "删除成功");
            } else {
                $this->Code(403, 403);
            }
        } else {
            $this->Code(200, false, "对不起,您没有权限");
        }
    }

    # 解绑微信
    public function unBindWx()
    {
        $id = $this->token["aid"];
        $role = $this->token["role"];
        if ($role == 1) {
            $aid = $_POST["id"];
            if ($_POST["id"] == "undefined") {
                $aid = $id;
            }
            $upInfo = [
                "avatar" => "",
                "openid" => ""
            ];
            Db::name("admin")
                ->where("aid", $aid)
                ->update($upInfo);
            $this->Code(200, "解绑成功");
        } else {
            $this->Code(200, false, "对不起,您没有权限");
        }
    }
}
